package com.fa7.android.example.listafacil;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CompraAdapter extends ArrayAdapter<Compra> {	
	private Context mContext;
	private int mResourceId;
	private List<Compra> mList;
	private CompraDB mDb;
	
	
	public CompraAdapter(Context context, int resource) {
		super(context, resource);
		mContext = context;
		mResourceId = resource;
		mDb = new CompraDB(context);
		mList = mDb.queryAll();
	}
	
	@Override
	public int getCount() {
		return mList.size();
	}
	@Override
	public Compra getItem(int position) {
		return mList.get(position);
	}
	
	@Override
	public long getItemId(int arg0) {
		return mList.get(arg0).getId();
	}
	

	@Override
	public View getView(int pos, View view, ViewGroup vg) {
		LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		Compra c = mList.get(pos);
	
		View v = (View)inflater.inflate(R.layout.adapter_layout, null);
		
		TextView tvName = (TextView)v.findViewById(R.id.adapter_compra_name);
		TextView tvValue = (TextView)v.findViewById(R.id.adapter_compra_value);
		TextView tvQtd = (TextView)v.findViewById(R.id.adapter_compra_qtd);
		TextView tvTotal = (TextView)v.findViewById(R.id.adapter_compra_total);
		ImageView iv = (ImageView)v.findViewById(R.id.adapter_img);
		
		tvName.setText(c.getName());
		tvValue.setText("R$ " + c.getValue());
		tvQtd.setText("Qtd: " + c.getQtd());
		tvTotal.setText("R$ " + (c.getValue() * c.getQtd()));
		
		String filename = c.getImgFilename();
		
		if (filename.isEmpty()) {
			filename = "img_default.png";
		}
		
		try {
			AssetManager assetManager = mContext.getAssets();
			InputStream istr = assetManager.open(filename);
			Bitmap bitmap = BitmapFactory.decodeStream(istr);
			
			iv.setImageBitmap(bitmap);
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		
		return v;	
	}
	
	@Override
	public void add(Compra c) {
		long id = mDb.insert(c);
		
		if (id != -1) {
			c.setId((int)id);
			mList.add(c);
			notifyDataSetChanged();	
		}
		
	}
	
	public void update(int pos, Compra c) {
		c.setId(getItem(pos).getId());
		mDb.update(c);
		mList.remove(pos);
		mList.add(pos, c);
		notifyDataSetChanged();
	}
	
	
}
